package com.fengxu.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

// 使用Netty搭建一个简易的http服务器
public class TestHttpServer {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 向管道中增加一个netty提供的hhtp编码，解码器
                        ch.pipeline().addLast("HttpServerCodec",new HttpServerCodec());
                        // 向管道中增加一个自定义的处理器(handler)
                        ch.pipeline().addLast("myHandler",new HttpServerHandler());
                    }
                });

        ChannelFuture channelFuture = serverBootstrap.bind(8000).sync();
        channelFuture.addListener(future -> {
            if(future.isSuccess()){
                System.out.println("绑定8000端口成功!");
            } else {
                System.out.println("绑定8000端口失败!");
            }
        });
        channelFuture.channel().closeFuture().sync();
    }

}
